package com.city.project.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class IpCheckFilter
 */
@WebFilter(urlPatterns = {"/*"}, initParams = {@WebInitParam(name = "ips", value = "0:0:0:0:0:0:0:1")})
public class IpCheckFilter implements Filter {
    String ips = null;

    /**
     * Default constructor.
     */
    public IpCheckFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        System.out.println("开始ip");
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        String uri = req.getRequestURI();
        System.out.println(uri);
        String appName = req.getServletContext().getContextPath();
        if (uri.equals(appName + "/hint/iperror.jsp")) {
            // 允许通过拦截器方法
            chain.doFilter(request, response);
        } else {
            String ip = req.getRemoteAddr();
            System.out.println(ip);

            if (!ips.contains(ip)) {
                res.sendRedirect(appName + "/hint/iperror.jsp");
            } else {
                chain.doFilter(request, response);
            }
        }
    }

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
        ips = fConfig.getInitParameter("ips");
    }

}
